import React, { useState, useEffect }  from 'react'
import { Col, Form, Table, Select, Input, DatePicker, Radio, InputNumber, message, Button } from 'antd'
import { formLayout } from '@/utils/utils'
import RenderButtom from '@/components/RenderButton'
import { overCoupon, couponJoinActivity, fetchAllCoupons } from '@/services/marketCenter/YHQ'
import SearchBox from '@/components/SearchBox'
const {RangePicker} = DatePicker
import moment from 'moment'
import { connect } from 'dva'
import { router } from 'umi'
const dateFormat = 'YYYY-MM-DD'

const YhqList = props => {
  const { form, couponClassify, dispatch, couponStatus, couponTypes, couponSendTypes } = props
  const { getFieldDecorator } = form
  const [total, setTotalPage] = useState(null)
  const [dataList, setDataList] = useState([])
  const [param, setParam] = useState({
    pageNo: 1,
    pageSize: 10
  })
  useEffect(() => {
    _fetchAllCoupons(param)
    dispatch({
      type: 'YHQ/getCouponClassify'
    })
  }, [])
  const _fetchAllCoupons = async (param) => {
    const res = await fetchAllCoupons(param)
    if (res.code == 0) {
      setDataList(res.data)
      setTotalPage(res.total)
    }
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      _fetchAllCoupons({
        ...param,
        ...values,
        startTime: values.dateTime ? `${moment(values.dateTime[0]).format(dateFormat)} 00:00:00` : '',
        endTime: values.dateTime ? `${moment(values.dateTime[1]).format(dateFormat)} 00:00:00` : '',
      })
    })
  }

  const pagination = {
    total: parseInt(total),
    onChange (page) {
      _fetchAllCoupons({
        ...param,
        pageNo: page
      })
    }
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (v, r, i) => {
        return (<span>{i+1}</span>)
      }
    },
    {
      title: '优惠券名称',
      dataIndex: 'couponName',
      key: 'couponName'
    },
    {
      title: '面值',
      dataIndex: 'couponType',
      key: 'couponType',
      render: (v, r, i) => {
        if (r.couponType == 1) {
          return (<span>{r.denomination}</span>)
        } else {
          return (<span>{r.discountRate + '%'}</span>)
        }
      }
    },
    {
      title: '使用条件',
      dataIndex: 'limitPrice',
      key: 'limitPrice',
      render: (v, r, i) => {
        return (<span>满 {v} 可使用</span>)
      }
    },
    {
      title: '使用期限',
      dataIndex: 'effectiveTime',
      key: 'effectiveTime',
      render: (v, r, i) => {
        return (<span>{r.effectiveTime + '-' + r.expirationTime}</span>)
      }
    },
    {
      title: '发放总量',
      dataIndex: 'lssuedQty',
      key: 'lssuedQty'
    },
    {
      title: '每人限领',
      dataIndex: 'receiveLimit',
      key: 'receiveLimit'
    },
    {
      title: '已领取',
      dataIndex: 'receiveCount',
      key: 'receiveCount'
    },
    {
      title: '已使用',
      dataIndex: 'useCount',
      key: 'useCount'
    },
    {
      title: '已退回',
      dataIndex: 'refundCount',
      key: 'refundCount'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (v, r, i) => {
        return (<>
          <Button onClick={() => editCurrRecord(r)} type="primary">编辑</Button>
          <Button onClick={() => overCurrRecord(r)} type="danger" style={{marginLeft: '10px'}}>结束</Button>
        </>)
      }
    },
  ]
  const editCurrRecord = (r) => {
    router.push({
      pathname: '/marketCenter/coupon/addCoupon',
      query: {
        couponId: r.id
      }
    })
  }
  const overCurrRecord = async (r) => {
    const res = await couponJoinActivity({couponId: r.id})
    if (res.code == 0) {
      if (res.data == 'true') {
        message.warning('此优惠券已参与活动，不能结束！')
      } else {
        const res_2 = await overCoupon({couponId: r.id})
        if (res_2.code == 0) {
          message.success('已结束！')
          _fetchAllCoupons(param)
        } else {
          message.error(r.msg);
      }
      }
    } else {
      message.error(res.msg)
    }
  }
  const getFields = () => {
    return (<>
      <Col span={8}>
        <Form.Item label="优惠券名称" labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('couponName', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`优惠券分类`} labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('sysClassId', {initialValue: '',})(
            <Select>
              {couponClassify && couponClassify.map((r, index) => <Select.Option key={index} value={r.id}>{r.className}</Select.Option>)}
            </Select>,
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`优惠券状态`} labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('status', {initialValue: '',})(
            <Select>
              {couponStatus.map((r, index) => <Select.Option key={index} value={r.value}>{r.label}</Select.Option>)}
            </Select>,
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label={`优惠券类型`} labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('couponType', {initialValue: '',})(
            <Select>
              {couponTypes.map((r, index) => <Select.Option key={index} value={r.value}>{r.label}</Select.Option>)}
            </Select>,
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="面额" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('minAmount', {defaultValue: 0})(<InputNumber min={0}/>)}
          <span> 至 </span>
          {getFieldDecorator('maxAmount', {defaultValue: 0})(<InputNumber min={0}/>)}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="有效日期" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator(`dateTime`, {})
            (<RangePicker />)}
        </Form.Item>
      </Col>
      <Col span={12}>
        <Form.Item label={`发放类型`} labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('couponSendType', {initialValue: '0',})(
            <Radio.Group>
              {couponSendTypes.map((r, index) => <Radio key={index} value={r.value}>{r.label}</Radio>)}
            </Radio.Group>,
          )}
        </Form.Item>
      </Col>
    </>)
  }

  return (<Form layout={formLayout}>
    <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
    <Table rowKey={record => record.id} pagination={pagination} size="small" columns={columns} dataSource={dataList}/>
  </Form>)
}

export default connect(({ YHQ }) => ({
  couponClassify: YHQ.couponClassify,
  couponStatus: YHQ.couponStatus,
  couponTypes: YHQ.couponTypes,
  couponSendTypes: YHQ.couponSendTypes,
}))(Form.create({})(YhqList))
